package com.b2b.message.admin.controller.auth.wx;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.b2b.bean.ResultBase;
import com.b2b.bean.ResultBean;
import com.b2b.constant.ResultEnum;
import com.b2b.message.admin.controller.SuperController;
import com.b2b.message.admin.plus.entity.WxConfig;
import com.b2b.message.admin.plus.entity.WxContentTemplate;
import com.b2b.message.admin.plus.entity.WxLogger;
import com.b2b.message.admin.plus.entity.WxTemplate;
import com.b2b.utils.Tools;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;

/**
 * 版权：上海极和信息科技有限公司
 * 功能：微信配置
 * 作者：朱伟峰
 * 邮箱：zhuweifeng24@gmail.com
 * 日期：2018年3月26日
 */
@Controller
@RequestMapping("/wx")
public class WxController extends SuperController
{
	private static final Logger logger = LoggerFactory.getLogger(WxController.class);
	
	@RequestMapping(value = "/conf/view")
	public String confView()
	{
		return "/wx/conf/list";
	}
	
	@ResponseBody
	@RequestMapping(value = "/conf/list")
	public ResultBean<Page<WxConfig>> confList()
	{
		Page<WxConfig> page = super.getPageInfo("sort", true);
		EntityWrapper<WxConfig> wrapper = new EntityWrapper<WxConfig>();
		String appid = request.getParameter("appid");
		if (!Tools.isTrimEmpty(appid))
			wrapper.like("appid", appid);
		String secret = request.getParameter("secret");
		if (!Tools.isTrimEmpty(secret))
			wrapper.like("secret", secret);
		String token = request.getParameter("token");
		if (!Tools.isTrimEmpty(token))
			wrapper.like("token", token);
		String status = request.getParameter("status");
		if (!Tools.isTrimEmpty(status))
			wrapper.where("status={0}", status);
		String type = request.getParameter("type");
		if (!Tools.isTrimEmpty(type))
			wrapper.where("type={0}", type);
		
		ResultBean<Page<WxConfig>> result = new ResultBean<Page<WxConfig>>();
		try
		{
			Page<WxConfig> pageInfo = wxConfigService.selectPage(page, wrapper);
			result.success(pageInfo);
		}
		catch (Exception e)
		{
			logger.error("", e);
			result.fail(ResultEnum.ERR_CATCH.getCode(), ResultEnum.ERR_CATCH.getMessage());
		}
		return result;
	}
	
	/**
	 * 详情
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/conf/detail")
	public String confDetail(@RequestParam("appid") String appid)
	{
		try
		{
			WxConfig wxConfig = wxConfigService.selectById(appid);
			if (wxConfig != null)
				request.setAttribute("bean", wxConfig);
		}
		catch (Exception e)
		{
			logger.error("", e);
		}
		return "/wx/conf/detail";
	}
	
	@RequestMapping(value = "/conf/addView")
	public String confAddView()
	{
		String appid = request.getParameter("appid");
		try
		{
			if (!Tools.isTrimEmpty(appid))
			{
				WxConfig wxConfig = wxConfigService.selectById(appid);
				if (wxConfig != null){
					request.setAttribute("bean", wxConfig);
				}
			}
		}
		catch (Exception e)
		{
			logger.error("", e);
		}
		return "/wx/conf/view";
	}
	
	@ResponseBody
	@RequestMapping(value = "/conf/add")
	public ResultBase confAdd(@Valid WxConfig wxConfig)
	{
		ResultBase result = new ResultBase();
		
		try
		{
			Integer status = wxConfig.getStatus();
			if (status == null) 
				wxConfig.setStatus(9);
			
			WxConfig _wxConfig = wxConfigService.selectById(wxConfig.getAppid());
			if (_wxConfig == null){
				wxConfig.setCreateTime(System.currentTimeMillis());
				wxConfig.setCreateUser(0l);
			}
			wxConfig.setUpdateTime(System.currentTimeMillis());
			wxConfig.setUpdateUser(0l);
			
			boolean flag = wxConfigService.insertOrUpdate(wxConfig);
			if (flag) 
				result.success();
			else
				result.fail(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMessage());
		}
		catch (Exception e)
		{
			logger.error("", e);
			result.fail(ResultEnum.ERR_CATCH.getCode(), ResultEnum.ERR_CATCH.getMessage());
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/conf/del")
	public ResultBase confDel(@RequestParam("appid") String appid, @RequestParam("status") int status)
	{
		ResultBase result = new ResultBase();
		
		try
		{
			WxConfig wxConfig = wxConfigService.selectById(appid);
			if (wxConfig == null)
			{
				result.fail(ResultEnum.ERR_1110.getCode(), ResultEnum.ERR_1110.getMessage());
				return result;
			}
			wxConfig.setStatus(status);
			boolean flag = wxConfigService.insertOrUpdate(wxConfig);
			if (flag) 
				result.success();
			else
				result.fail(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMessage());
		}
		catch (Exception e)
		{
			logger.error("", e);
			result.fail(ResultEnum.ERR_CATCH.getCode(), ResultEnum.ERR_CATCH.getMessage());
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/conf/delAll")
	public ResultBase confDelAll(@RequestParam("appid") String appids)
	{
		ResultBase result = new ResultBase();
		
		try
		{
			String message = "";
			String[] _appid = appids.split(",");
			if (_appid != null && _appid.length > 0)
			{
				int i = 0;
				for (String appid : _appid)
				{
					i ++;
					WxConfig wxConfig = wxConfigService.selectById(appid);
					if (wxConfig == null)
					{
						message += "第" + i + "条记录不存在,";
						continue;
					}
					wxConfig.setStatus(9);
					boolean flag = wxConfigService.insertOrUpdate(wxConfig);
					if (!flag) {
						message += "第" + i + "条记录保存失败,";
						continue;
					}
				}
			}
			if (Tools.isTrimEmpty(message)){
				result.success();
			} else{
				result.fail(ResultEnum.ERROR.getCode(), message);
			}
		}
		catch (Exception e)
		{
			logger.error("", e);
			result.fail(ResultEnum.ERR_CATCH.getCode(), ResultEnum.ERR_CATCH.getMessage());
		}
		return result;
	}
	
	/** ************************************************** 微信模板相关接口 ************************************************** */
	
	@RequestMapping(value = "/temp/view")
	public String tempView(@RequestParam("type") int type)
	{
		request.setAttribute("type", type);
		return "/wx/temp/list";
	}
	
	@ResponseBody
	@RequestMapping(value = "/temp/list")
	public ResultBean<Page<WxTemplate>> tempList(@RequestParam("type") int type)
	{
		Page<WxTemplate> page = super.getPageInfo("id", true);
		EntityWrapper<WxTemplate> wrapper = new EntityWrapper<WxTemplate>();
		wrapper.where("type={0}", type);
		
		String id = request.getParameter("id");
		if (!Tools.isTrimEmpty(id))
			wrapper.where("id={0}", id);
		String title = request.getParameter("title");
		if (!Tools.isTrimEmpty(title))
			wrapper.like("title", title);
		String appid = request.getParameter("appid");
		if (!Tools.isTrimEmpty(appid))
			wrapper.like("appid", appid);
		String templateCode = request.getParameter("templateCode");
		if (!Tools.isTrimEmpty(templateCode))
			wrapper.like("templateCode", templateCode);
		String status = request.getParameter("status");
		if (!Tools.isTrimEmpty(status))
			wrapper.where("status={0}", status);
		
		ResultBean<Page<WxTemplate>> result = new ResultBean<Page<WxTemplate>>();
		try
		{
			Page<WxTemplate> pageInfo = wxTemplateService.selectPage(page, wrapper);
			result.success(pageInfo);
		}
		catch (Exception e)
		{
			logger.error("", e);
			result.fail(ResultEnum.ERR_CATCH.getCode(), ResultEnum.ERR_CATCH.getMessage());
		}
		return result;
	}
	
	/**
	 * 详情
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/temp/detail")
	public String tempDetail(@RequestParam("id") long id)
	{
		try
		{
			WxTemplate wxTemplate = wxTemplateService.selectById(id);
			if (wxTemplate != null)
				request.setAttribute("bean", wxTemplate);
		}
		catch (Exception e)
		{
			logger.error("", e);
		}
		return "/wx/temp/detail";
	}
	
	@RequestMapping(value = "/temp/addView")
	public String tempAddView(@RequestParam("type") int type)
	{
		request.setAttribute("type", type);
		String id = request.getParameter("id");
		try
		{
			if (!Tools.isTrimEmpty(id))
			{
				WxTemplate wxTemplate = wxTemplateService.selectById(id);
				if (wxTemplate != null){
					request.setAttribute("bean", wxTemplate);
				}
			}
		}
		catch (Exception e)
		{
			logger.error("", e);
		}
		return "/wx/temp/view";
	}
	
	@ResponseBody
	@RequestMapping(value = "/temp/add")
	public ResultBase tempAdd(@Valid WxTemplate wxTemplate)
	{
		ResultBase result = new ResultBase();
		
		try
		{
			Integer status = wxTemplate.getStatus();
			if (status == null) 
				wxTemplate.setStatus(9);
			
			if (wxTemplate.getId() == null){
				wxTemplate.setCreateTime(System.currentTimeMillis());
				wxTemplate.setCreateUser(0l);
			}
			wxTemplate.setUpdateTime(System.currentTimeMillis());
			wxTemplate.setUpdateUser(0l);
			
			boolean flag = wxTemplateService.insertOrUpdate(wxTemplate);
			if (flag) 
				result.success();
			else
				result.fail(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMessage());
		}
		catch (Exception e)
		{
			logger.error("", e);
			result.fail(ResultEnum.ERR_CATCH.getCode(), ResultEnum.ERR_CATCH.getMessage());
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/temp/del")
	public ResultBase tempDel(@RequestParam("id") long id, @RequestParam("status") int status)
	{
		ResultBase result = new ResultBase();
		
		try
		{
			WxTemplate wxTemplate = wxTemplateService.selectById(id);
			if (wxTemplate == null)
			{
				result.fail(ResultEnum.ERR_1110.getCode(), ResultEnum.ERR_1110.getMessage());
				return result;
			}
			wxTemplate.setStatus(status);
			boolean flag = wxTemplateService.insertOrUpdate(wxTemplate);
			if (flag) 
				result.success();
			else
				result.fail(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMessage());
		}
		catch (Exception e)
		{
			logger.error("", e);
			result.fail(ResultEnum.ERR_CATCH.getCode(), ResultEnum.ERR_CATCH.getMessage());
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/conf/listType")
	public ResultBean<List<Map<String, Object>>> confListType()
	{
		ResultBean<List<Map<String, Object>>> result = new ResultBean<List<Map<String, Object>>>();
		
		try
		{
			EntityWrapper<WxConfig> wrapper = new EntityWrapper<WxConfig>();
			wrapper.where("status={0}", 0);
			String type = request.getParameter("type");
			if (!Tools.isTrimEmpty(type)){
				wrapper.and("type={0}", type);
			}
			wrapper.orderBy("sort", true);
			List<Map<String, Object>> list = wxConfigService.selectMaps(wrapper);
			if (list != null && !list.isEmpty())
			{
				result.success(list);
			}
			else
			{
				result.fail(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMessage());
			}
		}
		catch (Exception e)
		{
			logger.error("", e);
			result.fail(ResultEnum.ERR_CATCH.getCode(), ResultEnum.ERR_CATCH.getMessage());
		}
		return result;
	}
	
	/** ************************************************** 微信模板内容相关接口 ************************************************** */
	
	@ResponseBody
	@RequestMapping(value = "/temp/content/list")
	public ResultBean<Page<WxContentTemplate>> tempContentList(@RequestParam("wxTempId") long wxTempId)
	{
		Page<WxContentTemplate> page = super.getPageInfo("id", true);
		EntityWrapper<WxContentTemplate> wrapper = new EntityWrapper<WxContentTemplate>();
		wrapper.where("wxTempId={0}", wxTempId);
		ResultBean<Page<WxContentTemplate>> result = new ResultBean<Page<WxContentTemplate>>();
		try
		{
			Page<WxContentTemplate> pageInfo = wxContentTemplateService.selectPage(page, wrapper);
			result.success(pageInfo);
		}
		catch (Exception e)
		{
			logger.error("", e);
			result.fail(ResultEnum.ERR_CATCH.getCode(), ResultEnum.ERR_CATCH.getMessage());
		}
		return result;
	}
	
	@RequestMapping(value = "/temp/content/addView")
	public String tempContentAddView(@RequestParam("wxTempId") long wxTempId)
	{
		request.setAttribute("wxTempId", wxTempId);
		String id = request.getParameter("id");
		try
		{
			if (!Tools.isTrimEmpty(id))
			{
				WxContentTemplate wxContentTemplate = wxContentTemplateService.selectById(id);
				if (wxContentTemplate != null){
					request.setAttribute("bean", wxContentTemplate);
				}
			}
		}
		catch (Exception e)
		{
			logger.error("", e);
		}
		return "/wx/temp/viewContent";
	}
	
	@ResponseBody
	@RequestMapping(value = "/temp/content/add")
	public ResultBase tempContentAdd(@Valid WxContentTemplate wxContentTemplate)
	{
		ResultBase result = new ResultBase();
		
		try
		{
			if (wxContentTemplate.getId() == null){
				wxContentTemplate.setCreateTime(System.currentTimeMillis());
				wxContentTemplate.setCreateUser(0l);
			}
			wxContentTemplate.setUpdateTime(System.currentTimeMillis());
			wxContentTemplate.setUpdateUser(0l);
			wxContentTemplate.setStatus(0);
			Integer enlarge = wxContentTemplate.getEnlarge();
			if (enlarge == null) 
				wxContentTemplate.setEnlarge(0);
			
			boolean flag = wxContentTemplateService.insertOrUpdate(wxContentTemplate);
			if (flag) 
				result.success();
			else
				result.fail(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMessage());
		}
		catch (Exception e)
		{
			logger.error("", e);
			result.fail(ResultEnum.ERR_CATCH.getCode(), ResultEnum.ERR_CATCH.getMessage());
		}
		return result;
	}
	
	@ResponseBody
	@RequestMapping(value = "/temp/content/del")
	public ResultBase tempContentDel(@RequestParam("id") long id)
	{
		ResultBase result = new ResultBase();
		
		try
		{
			WxContentTemplate wxContentTemplate = wxContentTemplateService.selectById(id);
			if (wxContentTemplate == null)
			{
				result.fail(ResultEnum.ERR_1110.getCode(), ResultEnum.ERR_1110.getMessage());
				return result;
			}
			boolean flag = wxContentTemplateService.deleteById(id);
			if (flag) 
				result.success();
			else
				result.fail(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMessage());
		}
		catch (Exception e)
		{
			logger.error("", e);
			result.fail(ResultEnum.ERR_CATCH.getCode(), ResultEnum.ERR_CATCH.getMessage());
		}
		return result;
	}
	
	/** ************************************************** 微信日志相关接口 ************************************************** */
	
	@RequestMapping(value = "/logs/view")
	public String logsView()
	{
		return "/wx/logs/list";
	}
	
	@ResponseBody
	@RequestMapping(value = "/logs/list")
	public ResultBean<Page<WxLogger>> logsList()
	{
		Page<WxLogger> page = super.getPageInfo("id", false);
		EntityWrapper<WxLogger> wrapper = new EntityWrapper<WxLogger>();

		String status = request.getParameter("status");
		if (!Tools.isTrimEmpty(status))
			wrapper.where("status={0}", status);
		String openId = request.getParameter("openId");
		if (!Tools.isTrimEmpty(openId))
			wrapper.and("openId={0}", openId);
		String code = request.getParameter("code");
		if (!Tools.isTrimEmpty(code))
		{
			if ("0".equals(code)) wrapper.eq("code", 0);
			else wrapper.ne("code", 0);
		}
		String wxTempId = request.getParameter("wxTempId");
		if (!Tools.isTrimEmpty(wxTempId))
			wrapper.and("wxTempId={0}", wxTempId);
		
		ResultBean<Page<WxLogger>> result = new ResultBean<Page<WxLogger>>();
		try
		{
			Page<WxLogger> pageInfo = wxLoggerService.selectPage(page, wrapper);
			result.success(pageInfo);
		}
		catch (Exception e)
		{
			logger.error("", e);
			result.fail(ResultEnum.ERR_CATCH.getCode(), ResultEnum.ERR_CATCH.getMessage());
		}
		return result;
	}
	
	/**
	 * 详情
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/logs/detail")
	public String logsDetail(@RequestParam("id") long id)
	{
		try
		{
			WxLogger wxLogger = wxLoggerService.selectById(id);
			if (wxLogger != null)
				request.setAttribute("bean", wxLogger);
		}
		catch (Exception e)
		{
			logger.error("", e);
		}
		return "/wx/logs/detail";
	}
	
//	@ResponseBody
//	@RequestMapping(value = "/logs/del")
//	public ResultBase logsDel(@RequestParam("id") long id)
//	{
//		ResultBase result = new ResultBase();
//		
//		try
//		{
//			WxLogger wxLogger = wxLoggerService.selectById(id);
//			if (wxLogger == null)
//			{
//				result.fail(ResultEnum.ERR_1110.getCode(), ResultEnum.ERR_1110.getMessage());
//				return result;
//			}
//			boolean flag = wxLoggerService.deleteById(id);
//			if (flag) 
//				result.success();
//			else
//				result.fail(ResultEnum.ERROR.getCode(), ResultEnum.ERROR.getMessage());
//		}
//		catch (Exception e)
//		{
//			logger.error("", e);
//			result.fail(ResultEnum.ERR_CATCH.getCode(), ResultEnum.ERR_CATCH.getMessage());
//		}
//		return result;
//	}
	
}
